import java.io.File;
import java.io.FilenameFilter;

import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.AudioHeader;


public class AverageMP3LengthMain {

	private int numMp3 = 0;
	private int totalLength = 0;
	
	public AverageMP3LengthMain(String[] dirs) {
		for (int i = 0; i < dirs.length; i++) {
			String currentDir = dirs[i];
			int currentLength = getTotalMp3Length(dirs[i]);
			System.out.println("Folder \"" + currentDir + "\" length = \n"
				+ currentLength + " s.");
			totalLength += currentLength;
		}
		System.out.println("\nTotal length = \n"
			+ totalLength + " s.");
		
		int nbDays = totalLength/3600/24;
		int nbHours = (totalLength -nbDays*3600*24)/3600;
		System.out.println("\nTotal length = \n"
			+ nbDays + " days and " + nbHours + " hours.");
		
		int averageLength = totalLength/numMp3;
		System.out.println("\nAverage length = \n"
				+ averageLength + " s.");
		
		int nbMinutes = averageLength/60;
		int nbSeconds = averageLength % 60;
		System.out.println("\nAverage length = \n"
				+ nbMinutes + " min " + nbSeconds + " seconds.");
		
	}

	private int getTotalMp3Length(String dir) {
		int totalLength = 0;
		
		File fDir = new File(dir);
		String[] mp3s = fDir.list(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String filename) {
				return (filename.endsWith(".mp3"));
			}
		});
		
		for (int i = 0; i < mp3s.length; i++) {
			numMp3++;
			try {
				File currentMp3 = new File(fDir, mp3s[i]);
				AudioFile f = AudioFileIO.read(currentMp3);
				AudioHeader audioHeader = f.getAudioHeader();
				int length = audioHeader.getTrackLength();
				totalLength += length;
			} catch (Throwable ioe) {
				System.err.println("Cannot read MP3.");
				System.err.println(ioe);
			}
		}
		return totalLength;
	}

	public static void main(String[] args) {
		String[] dirs = {"F:/_Calme", "F:/_Good", "F:/_Energie", "F:/_Styles/Hip Hop",
			"F:/_Styles/Poubelle"};
		new AverageMP3LengthMain(dirs);
	}
}
